package com.sam.learn.service.impl;

import com.sam.learn.config.MailSenderConfig;
import com.sam.learn.dto.MailDTO;
import com.sam.learn.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @classname: MailServiceImpl
 * @description: TODO
 * @Author: sam
 * @date: 2022/10/23 22:26
 */
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    MailSenderConfig senderConfig;

    @Override
    public void send(MailDTO mailDTO) {
        JavaMailSenderImpl mailSender = senderConfig.getSender();
        // 创建一个SimpleMailMessage对象
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            //发件人
            helper.setFrom(mailSender.getUsername());
            //收件人 这个收件人可以是数组的，只是我这只需要单个 就没多做了。
            helper.setTo(mailDTO.getMail());
            helper.setSubject("验证码");

            //将邮件内容设置为html格式
            String content = "<html><body><h3><font color=\"red\">" + "大家好，这是springboot发送的HTML邮件，有附件哦" + "</font></h3></body></html>";
            // 发送
            helper.setText(content, true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        mailSender.send(mimeMessage);
    }

    @Override
    public void clear() {
        senderConfig.clear();
    }
}
